// Copyright (C) 2008 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include "MemGroup.h"

namespace lagniappe
{

MemGroup::MemGroup()
{
}

MemGroup::~MemGroup()
{
}

ProcElement *
MemGroup::getFreeProc(Operator * o)
{
	assert(!freeProcList.empty());
	ProcElement * tempProc = NULL;
	tempProc = freeProcList.front();
	assert(tempProc != NULL);
	freeProcList.pop_front();
	procToOpMap[tempProc].push_back(o);
	opToProcMap[o].push_back(tempProc);
	return tempProc;
}

bool
MemGroup::hasFree(bool initial)
{
	bool ret = true;
	if(initial) {
		unsigned int freeProcBuffer = static_cast<unsigned int>(floor(procToOpMap.size() * BUFFER_CONST));
		if(freeProcList.size() <= freeProcBuffer) ret = false; 
	}
	else {
		ret = !freeProcList.empty();
	}
	return ret;
}

void 
MemGroup::insertProcessor(ProcElement * p) 
{
	freeProcList.push_back(p);
	procToOpMap[p].push_back(NULL);
	p->setMemGroup(this);
}

void
MemGroup::revokeOpProc(Operator * op, ProcElement * p)
{
	std::list<ProcElement *> & procList = opToProcMap[op];
	for(std::list<ProcElement*>::iterator iter = procList.begin();
		iter != procList.end(); ++iter) {
		if(*iter == p) procList.erase(iter);
		break;
	}
	std::list<Operator *> & opList = procToOpMap[p];
	for(std::list<Operator *>::iterator iter = opList.begin();
		iter != opList.end(); ++iter) {
		if(*iter == op) opList.erase(iter);
		break;
	}
}



}
